<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="../../bower_components/paper-styles/typography.html">
<link rel="import" href="../../bower_components/paper-button/paper-button.html">
<link rel="import" href="../../bower_components/paper-input/paper-textarea.html">
<link rel="import" href="../../bower_components/paper-dropdown-menu/paper-dropdown-menu.html">
<link rel="import" href="../../bower_components/paper-listbox/paper-listbox.html">
<link rel="import" href="../../bower_components/paper-progress/paper-progress.html">
<dom-module id="detach-volume">
    <template>
        <style include="shared-styles dialogs">
        :host {
            width: 100%;
        }

        :host .btn-group {
            margin: 0 0 24px 0;
        }

        paper-dialog {
            min-width: 360px;
        }

        .grey {
            opacity: 0.54;
        }

        .progress {
            margin: 24px -24px 24px -24px;
            width: 100%;
        }

        .progress paper-progress {
            width: 100%;
        }

        .error {
            color: var(--red-color);
            align-self: flex-end;
            padding: 8px;
            font-size: 0.9em;
        }

        iron-icon {
            color: inherit;
        }

        .errormsg-container {
            color: var(--red-color);
            padding-left: 24px;
            padding-right: 24px;
            margin-bottom: 0;
        }

        .errormsg-container iron-icon {
            color: inherit;
            padding-right: 8px;
        }
        </style>
        <paper-dialog id="detachDialogModal" entry-animation="scale-up-animation" exit-animation="fade-out-animation" with-backdrop>
            <h2>Detach Volume</h2>
            <paper-dialog-scrollable>
                <p>
                    <span class="grey"> Choose the machines to detach from. </span>
                    <paper-dropdown-menu label="Select machine" horizontal-align="left">
                        <paper-listbox slot="dropdown-content" id="machines" attr-for-selected="value" selected="{{selectedMachineId}}" class="dropdown-content">
                            <template is="dom-repeat" items="[[machines]]" as="machine">
                                <paper-item value="[[machine.id]]">[[machine.name]]</paper-item>
                            </template>
                        </paper-listbox>
                    </paper-dropdown-menu>
                </p>
            </paper-dialog-scrollable>
            <div class="progress">
                <paper-progress id="progress" indeterminate hidden$="[[!loading]]"></paper-progress>
                <paper-progress id="progresserror" class="progresserror" value="100" hidden$="[[!formError]]"></paper-progress>
                <p id="progressmessage" class="errormsg-container" hidden$="[[!formError]]">
                    <iron-icon icon="icons:error-outline"></iron-icon><span id="errormsg"></span>
                </p>
            </div>
            <div class="clearfix btn-group">
                <paper-button dialog-dismiss>
                    Cancel
                </paper-button>
                <paper-button class="blue" on-tap="detachVolume" disabled$="[[!selectedMachineId]]">
                    Detach from machine
                </paper-button>
            </div>
        </paper-dialog>
        <iron-ajax id="detachVolumeRequest" method="PUT" on-response="_detachVolumeResponse" on-error="_detachVolumeError" on-request="_detachVolumeRequest" handle-as="xml" loading="{{loading}}"></iron-ajax>
    </template>
    <script>
    Polymer({
        is: 'detach-volume',

        properties: {
            items: {
                type: Array,
                notify: true
            },
            selectedMachineId: {
                type: String,
                value: false
            },
            machines: {
                type: Array,
                value: []
            },
            loading: {
                type: Boolean,
                value: false
            },
            formError: {
                type: Boolean,
                value: false
            }
        },
        listeners: {
            // 'iron-select' : 'computedSelectedMachineId'
        },
        ready: function() {},
        computedSelectedMachineId: function(selected) {
            // this.set('selectedMachineId', this.$.machines.selected || '');
        },
        _openDialog: function(e) {
            this.set('selectedMachineId', false);
            this.set('formError', false);
            this.$.detachDialogModal.open();
        },
        _closeDialog: function(e) {
            this.set('formError', false);
            this.$.detachDialogModal.close();
        },
        detachVolume: function(e) {
            var request = this.$.detachVolumeRequest,
                items = this.items.slice(0),
                selectedMachineId = this.selectedMachineId;
            var run = function(el) {
                var item = items.shift(),
                    itemType,
                    itemId;
                if (item.length) {
                    chunks = item.split(':'),
                        itemId = chunks[2],
                        cloudId = chunks[1];
                } else {
                    itemId = item.external_id;
                    cloudId = item.cloud;
                }
                request.url = "/api/v1/clouds/" + cloudId + "/volumes/" + itemId;
                request.body = { action: 'detach', machine: selectedMachineId };
                request.headers["Content-Type"] = 'application/json';
                request.headers["Csrf-Token"] = CSRF_TOKEN;
                request.generateRequest();

                if (items.length) {
                    run(el);
                }
            }
            run(this);
        },
        _detachVolumeRequest: function() {
            this.clearError();
            var logMessage = 'Sending request to detach volume on machine.';
            this.dispatchEvent(new CustomEvent('performing-action', { bubbles: true, composed: true, detail: { log: logMessage } }));

        },
        _detachVolumeResponse: function(e) {
            console.log(e, e.detail);
            this._closeDialog();
            this.dispatchEvent(new CustomEvent('action-finished', { bubbles: true, composed: true, detail: { success: true } }));

            this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail: { msg: 'Detach request sent successfully. Review in machine logs.', duration: 5000 } }));

        },
        _detachVolumeError: function(e) {
            console.log(e, e.detail);
            this.$.errormsg.textContent = e.detail.request.xhr.response;
            this.set('formError', true);
        },
        clearError: function() {
            this.set('formError', false);
            this.$.errormsg.textContent = '';
            this.$.detachDialogModal.refit();
        },
    });
    </script>
</dom-module>